package com.lyhengtongwl.zqsnews.ui.fragment;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.adapter.TaskAdapter;
import com.lyhengtongwl.zqsnews.base.BaseFragment;
import com.lyhengtongwl.zqsnews.entity.NewsBaseEntity;
import com.lyhengtongwl.zqsnews.entity.NewsGG;
import com.lyhengtongwl.zqsnews.entity.TaskEntity;
import com.lyhengtongwl.zqsnews.manage.DBManager;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.net.UpClickCount;
import com.lyhengtongwl.zqsnews.ui.activity.EarnActivity;
import com.lyhengtongwl.zqsnews.ui.activity.MainActivity;
import com.lyhengtongwl.zqsnews.ui.activity.NewsMineInfoActivity;
import com.lyhengtongwl.zqsnews.ui.activity.NewsNoticeActivity;
import com.lyhengtongwl.zqsnews.ui.activity.NewsSettingActivity;
import com.lyhengtongwl.zqsnews.ui.activity.NewsWebCommonActivity;
import com.lyhengtongwl.zqsnews.ui.activity.NewsWebGLActivity;
import com.lyhengtongwl.zqsnews.ui.activity.WithDrawNowActivity;
import com.lyhengtongwl.zqsnews.ui.activity.WithDrawRecordActivity;
import com.lyhengtongwl.zqsnews.utils.AppConfig;
import com.lyhengtongwl.zqsnews.utils.CheckApkExist;
import com.lyhengtongwl.zqsnews.utils.CopyUtils;
import com.lyhengtongwl.zqsnews.utils.FTYUtils;
import com.lyhengtongwl.zqsnews.utils.ImRezUtils;
import com.lyhengtongwl.zqsnews.utils.NewsToastUtils;
import com.lyhengtongwl.zqsnews.utils.SPUtils;
import com.lyhengtongwl.zqsnews.utils.ScreenUtil;
import com.lyhengtongwl.zqsnews.widget.CenterDialog;
import com.lyhengtongwl.zqsnews.widget.ScrollTextViewNotice;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

public class NewsWithDrawFragment extends BaseFragment {
    @BindView(R.id.view_status_bar_place)
    View statusBarPlace;
    @BindView(R.id.tv_login)
    TextView tv_login;//手机号
    @BindView(R.id.tv_money)
    TextView tv_money;//账户余额
    @BindView(R.id.tv_todayM)
    TextView tv_todayM;//今日收入
    @BindView(R.id.tv_ljm)
    TextView tv_ljm;//累计收益
    @BindView(R.id.iv_banner)
    ImageView iv_banner;
    @BindView(R.id.civ_head)
    ImageView civ_head;
    @BindView(R.id.scrollIndicatorUp)
    ScrollTextViewNotice scrollIndicatorUp;//滚动的字样
    @BindView(R.id.tv_1)
    TextView tv_1;
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.recycleView_task)
    RecyclerView recycleView_task;
    @BindView(R.id.news_task)
    LinearLayout news_task;
    @BindView(R.id.iv_notice)
    ImageView ivNotice;
    private TaskAdapter taskAdapter;
    private List<TaskEntity> taskList = new ArrayList<>();
    private String avatar;
    private String mobile;
    private Integer balance;
    private List<String> ggList = new ArrayList<>();
    private List<String> ggId = new ArrayList<>();
    private String key;
    private String nickName;
    private List<NewsGG> newsGGS = new ArrayList<>();
    private boolean isFirst = true;

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public View setContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_newshome, null);
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String str) {
        //获取出价记录  然后进行设置
        try {
            switch (str) {
                case "refreshNew": //重新刷数据
                    if (!isFirst) {
                        getUserInCome();
                    }
                    break;
                case "changeState":
                    ivNotice.setImageResource(R.drawable.icon_notice1);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
        ViewGroup.LayoutParams params = statusBarPlace.getLayoutParams();
        params.height = ScreenUtil.getStatusBarHeight(getContext());
        statusBarPlace.setLayoutParams(params);
    }

    @OnClick({R.id.ll_wd_now, R.id.ll_jt, R.id.ll_wdCord, R.id.ll_gl, R.id.civ_head, R.id.tv_login,
            R.id.rel_forward, R.id.rel_enlighten, R.id.rel_faq, R.id.iv_setting
            , R.id.ll_qiandao, R.id.tv_copy, R.id.rel_addGroup, R.id.iv_notice, R.id.tv_ck, R.id.tv_tt,
            R.id.tv_money, R.id.tv_todayM, R.id.tv_sr, R.id.tv_ljsy, R.id.tv_ljm})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.ll_wd_now://立即提现
                startActivity(new Intent(getActivity(), WithDrawNowActivity.class));
                break;
            case R.id.ll_jt://收入明细
                startActivity(new Intent(getActivity(), EarnActivity.class));
                break;
            case R.id.ll_wdCord://提现记录
                startActivity(new Intent(getActivity(), WithDrawRecordActivity.class));
                break;
            case R.id.ll_gl://赚钱攻略
                UpClickCount.getInstance(getActivity()).upClick("strategy", "攻略");
                startActivity(new Intent(getActivity(), NewsWebGLActivity.class).putExtra("url", AppConfig.getInstance(App.getContext()).get("strategyUrl")).putExtra("isDefault", "true")
                );
                break;
            case R.id.civ_head:
            case R.id.tv_login://个人中心资料设置
                startActivity(new Intent(getActivity(), NewsMineInfoActivity.class));
                break;
            case R.id.rel_forward://转发赚钱
                ((MainActivity) getActivity()).getTabLayout(0).setCurrentTab(0);
                break;
            case R.id.rel_enlighten://收徒赚钱
                ((MainActivity) getActivity()).getTabLayout(1).setCurrentTab(1);
                break;
            case R.id.rel_faq://常见问题
                UpClickCount.getInstance(getActivity()).upClick("question", "常见问题");
                startActivity(new Intent(getActivity(), NewsWebCommonActivity.class).putExtra("url", AppConfig.getInstance(App.getContext()).get("problemUrl")));
                break;
            case R.id.iv_setting://设置
                startActivity(new Intent(getActivity(), NewsSettingActivity.class));
                break;
            case R.id.ll_qiandao://签到
                new CenterDialog(R.layout.item_qd_layout, getActivity()).showQD();
                break;
            case R.id.tv_copy://复制内容
                CopyUtils.copyText(Objects.requireNonNull(getActivity()), AppConfig.getInstance(App.getContext()).get("wechat"));
                openWX();
                break;
            case R.id.rel_addGroup://加qq群
                if (!joinQQGroup(key)) {
                    NewsToastUtils.showToast(getActivity(), "未安装手Q或安装的版本不支持！");
                }
                break;
            case R.id.iv_notice://查看所有通知
                SPUtils.put(App.getContext(), "isHaveMsg", false);
                startActivity(new Intent(getActivity(), NewsNoticeActivity.class));
                break;
            case R.id.tv_ck://查看
                UpClickCount.getInstance(getActivity()).upClick("msgContent", "消息详情");
                if (ggId.size() > 0)
                    startActivity(new Intent(getActivity(), NewsWebCommonActivity.class).putExtra("url", AppConfig.getInstance(App.getContext()).get("newUrl") + "?id=" + ggId.get(scrollIndicatorUp.getPosition())));
                break;
            case R.id.tv_tt://跳转收入详情
            case R.id.tv_money:
            case R.id.tv_todayM:
            case R.id.tv_sr:
            case R.id.tv_ljsy:
            case R.id.tv_ljm:
                startActivity(new Intent(getActivity(), EarnActivity.class));
                break;


        }
    }

    //打开微信
    public void openWX() {
        if (CheckApkExist.checkApkExist(getActivity(), "com.tencent.mm")) {
            Intent intent = new Intent();
            ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(cmp);
            getActivity().startActivity(intent);
        } else {
            NewsToastUtils.showToast(getActivity(), "未安装手微信或安装的版本不支持！");
        }
    }

    /****************
     *
     * 发起添加群流程。群号：赚钱树(818255922) 的 key 为： m871lMbeHXSE7V5_XEg5HaZQ5-9z-r-2
     * 调用 joinQQGroup(m871lMbeHXSE7V5_XEg5HaZQ5-9z-r-2) 即可发起手Q客户端申请加群 赚钱树(818255922)
     *
     * @param key 由官网生成的key
     * @return 返回true表示呼起手Q成功，返回fals表示呼起失败
     ******************/
    private boolean joinQQGroup(String key) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + key));
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            startActivity(intent);
            return true;
        } catch (Exception e) {
            // 未安装手Q或安装的版本不支持
            return false;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (isFirst) {
                LinearLayoutManager manager = new LinearLayoutManager(getActivity());
                if (taskAdapter == null) {
                    taskAdapter = new TaskAdapter(getActivity(), getActivity().getSupportFragmentManager(), taskList);
                }
                recycleView_task.setHasFixedSize(true);
                recycleView_task.setLayoutManager(manager);
                // 第一种，直接取消动画
                RecyclerView.ItemAnimator animator = recycleView_task.getItemAnimator();
                if (animator instanceof SimpleItemAnimator) {
                    ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
                }
                recycleView_task.setAdapter(taskAdapter);
            }
            isFirst = false;
            getUserInCome();
            getGGTitle();
        } else {
            scrollIndicatorUp.stopScroll();
        }
    }

    //获取title信息
    @SuppressLint("SetTextI18n")
    private void getGGTitle() {
        tv1.setText(AppConfig.getInstance(App.getContext()).get("wechat"));
        tv_1.setText("赚钱更多加QQ群" + AppConfig.getInstance(App.getContext()).get("qqGroup"));
        key = AppConfig.getInstance(App.getContext()).get("groupKey");
        ggList.clear();
        ggList = DBManager.getNewsTitle();
        if (ggList.size() > 0) {
            scrollIndicatorUp.setList(ggList);
            scrollIndicatorUp.startScroll();
        } else {
            getGG();
        }

    }

    //初始化数据
    private void getUserInCome() {
        boolean isHave = (boolean) SPUtils.get(App.getContext(), "isHaveMsg", false);
        if (isHave) {
            ivNotice.setImageResource(R.drawable.icon_notice1);
        } else {
            ivNotice.setImageResource(R.drawable.icon_notice_no);
        }
        Task.getApiService().getByUserIncome().enqueue(new MyCallback<NewsBaseEntity>(getActivity()) {
            @SuppressLint("SetTextI18n")
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                try {
                    String jsonStr = JSONObject.toJSONString(response.body().getData());
                    JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                    Integer allIncome = jsonObject.getInteger("allIncome");
                    Integer authStatus = jsonObject.getInteger("authStatus");
                    SPUtils.put(App.getContext(), "authStatus", authStatus + "");
                    String banner = jsonObject.getString("banner");

                    Integer todayIncome = jsonObject.getInteger("todayIncome");
                    String userInfo = JSONObject.toJSONString(jsonObject.getJSONObject("userinfo"));
                    JSONObject jsonObject1 = JSONObject.parseObject(userInfo);
                    balance = jsonObject1.getInteger("balance");
                    SPUtils.put(App.getContext(), "balance", balance + "");
                    nickName = jsonObject1.getString("nickName");
                    SPUtils.put(App.getContext(), "nickName", nickName);
                    mobile = jsonObject1.getString("mobile");
                    SPUtils.put(App.getContext(), "mobile", mobile + "");
                    Integer userId = jsonObject1.getInteger("userId");
                    avatar = jsonObject1.getString("avatar");
                    SPUtils.put(App.getContext(), "avatar", avatar + "");
                    tv_login.setText(mobile.replace(mobile.substring(3, 7), "****"));
                    tv_money.setText(FTYUtils.fenToYuan(balance) + "");
                    tv_todayM.setText(FTYUtils.fenToYuan(todayIncome) + "");
                    tv_ljm.setText(FTYUtils.fenToYuan(allIncome) + "");
                    Integer depositNum = jsonObject1.getInteger("depositNum");//提现次数
                    SPUtils.put(App.getContext(), "depositNum", depositNum + "");
                    String isFirstDeposit = jsonObject1.getString("isFirstDeposit");
                    SPUtils.put(App.getContext(), "isFirstDeposit", isFirstDeposit);
                    String path = SPUtils.get(App.getContext(), "head", "") + "";
                    if (!"".equals(path)) {
                        civ_head.setImageBitmap(ImRezUtils.getBitmap(path));
                    } else {
                        if ("".equals(avatar)) {
                            Picasso.with(App.getContext()).load(R.mipmap.head).into(civ_head);
                        } else {
                            Picasso.with(App.getContext()).load(avatar).into(civ_head);
                        }
                    }
                    Picasso.with(App.getContext()).load(banner).memoryPolicy(MemoryPolicy.NO_CACHE).resize(670, 96).into(iv_banner);//原图  1005  144
                    if (depositNum == 0) {
                        setTask();
                    } else {
                        news_task.setVisibility(View.GONE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //获取新手任务列表
    private void setTask() {
        taskList.clear();
        int userId = Integer.parseInt(SPUtils.get(App.getContext(), "userId", "0") + "");
        Task.getApiService().getTask(userId).enqueue(new MyCallback<NewsBaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                if ("1".equals(response.body().getCode())) {
                    String jsonStr = JSONObject.toJSONString(response.body().getData()) + "";
                    if (!jsonStr.equals("")) {
                        JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                        if (jsonArray.size() > 0) {
                            news_task.setVisibility(View.VISIBLE);
                            for (int i = 0; i < jsonArray.size(); i++) {
                                TaskEntity taskEntity = new TaskEntity();
                                taskEntity.setDescription(jsonArray.getJSONObject(i).getString("content"));
                                taskEntity.setImgUrl(jsonArray.getJSONObject(i).getString("avatar"));
                                taskEntity.setMoney(jsonArray.getJSONObject(i).getInteger("money") + "");
                                taskEntity.setState(jsonArray.getJSONObject(i).getInteger("status") + "");
                                taskEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                                taskEntity.setTaskType(jsonArray.getJSONObject(i).getInteger("taskId") + "");
                                taskList.add(taskEntity);
                            }
                            taskAdapter.notifyDataSetChanged();
                        }
                    }


                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //获取公告列表
    private void getGG() {
        Task.getApiService().getGG().enqueue(new MyCallback<NewsBaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                try {
                    if ("1".equals(response.body().getCode())) {
                        String jsonStr = JSONObject.toJSONString(response.body().getData());
                        JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                        newsGGS.clear();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObject = JSON.parseObject(jsonArray.get(i).toString());
                            ggList.add(jsonObject.getString("title"));
                            ggId.add(jsonObject.getInteger("id") + "");
                        }
                        scrollIndicatorUp.setList(ggList);
                        scrollIndicatorUp.startScroll();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }
}
